/**
 * 店主申请审核系统
 */

// 全局变量
let applications = [];
let currentPage = 1;
let rowsPerPage = 10;
let totalPages = 0;
let totalApplications = 0;

// DOM元素
const tableBody = document.getElementById('tableBody');
const pageNumbers = document.getElementById('pageNumbers');
const prevPage = document.getElementById('prevPage');
const nextPage = document.getElementById('nextPage');
const pageSizeSelect = document.getElementById('pageSize');
const username = document.getElementById('username');
const statusFilter = document.getElementById('statusFilter');
const searchBtn = document.getElementById('searchBtn');
const loader = document.getElementById('compact-loader');

// 统计元素
const totalApplicationsElement = document.getElementById('totalApplications');
const pendingApplicationsElement = document.getElementById('pendingApplications');
const approvedApplicationsElement = document.getElementById('approvedApplications');
const rejectedApplicationsElement = document.getElementById('rejectedApplications');

// 初始化页面
function init() {
    renderTable();
    addEventListeners();
}

// 渲染表格
function renderTable() {
    showLoader();

    const searchData = {
        username: username.value || '',
        status: statusFilter.value || '',
        page: currentPage,
        pageSize: rowsPerPage
    };

    console.log('请求参数:', searchData);

    $.ajax({
        url: 'userAduit/list',
        type: 'POST',
        data: searchData,
        success: function (data) {
            if (data.code == 200) {
                console.log('响应数据:', data);

                // 直接使用后端返回的数据，不需要前端再次分页和过滤
                applications = data.data.rows || [];
                totalApplications = data.data.total;
                totalPages = Math.ceil(totalApplications / rowsPerPage);

                console.log('分页信息:', {
                    currentPage,
                    totalPages,
                    totalApplications,
                    rowsPerPage
                });

                // 渲染表格内容
                renderTableBody();

                // 渲染分页控件
                renderPagination();

                hideLoader();
            } else {
                console.error('API返回错误:', data.message);
                showError('获取申请数据失败: ' + data.message);
                hideLoader();
            }
        },
        error: function(xhr, status, error) {
            console.error('请求失败:', error);
            showError('网络请求失败，请稍后重试');
            hideLoader();
        }
    });
}

// 渲染表格内容
function renderTableBody() {
    tableBody.innerHTML = '';

    if (applications.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center py-4 text-muted">
                    <i class="bi bi-inbox"></i> 暂无申请数据
                </td>
            </tr>
        `;
        return;
    }

    applications.forEach(application => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${application.id}</td>
            <td>
                ${application.icon ?
            `<img src="${application.icon}" class="user-avatar" alt="${application.username}的头像">` :
            `<div class="user-avatar-placeholder"><i class="bi bi-person"></i></div>`
        }
            </td>
            <td>${escapeHtml(application.username || '')}</td>
            <td>${application.createdTime}</td>
            <td>
                <span class="status-badge ${getStatusClass(application.status)}">
                    ${getStatusText(application.status)}
                </span>
            </td>
            <td>
                <button class="btn-view" data-id="${application.id}">
                    <i class="bi bi-eye"></i> 查看
                </button>
                ${application.status === 1 ? `
                <button class="btn-approve" data-id="${application.id}">
                    <i class="bi bi-check-lg"></i> 通过
                </button>
                <button class="btn-reject" data-id="${application.id}">
                    <i class="bi bi-x-lg"></i> 拒绝
                </button>
                ` : ''}
            </td>
        `;
        tableBody.appendChild(row);
    });
}

// 更新统计信息
function updateStatistics() {
    // 这里可以添加统计信息的更新逻辑
    if (totalApplicationsElement) {
        totalApplicationsElement.textContent = totalApplications;
    }
}

// 获取状态类名
function getStatusClass(status) {
    console.log('状态值:', status, '类型:', typeof status);
    switch(parseInt(status)) {
        case 1: return 'status-pending';
        case 0: return 'status-approved';
        case 2: return 'status-rejected';
        default: return '';
    }
}

// 获取状态文本
function getStatusText(status) {
    switch(parseInt(status)) {
        case 1: return '待审核';
        case 0: return '已通过';
        case 2: return '已拒绝';
        default: return '未知';
    }
}

// 渲染分页
function renderPagination() {
    console.log('渲染分页 - 当前页:', currentPage, '总页数:', totalPages, '总申请数:', totalApplications);

    pageNumbers.innerHTML = '';

    // 上一页按钮状态
    prevPage.disabled = currentPage === 1;

    // 下一页按钮状态
    nextPage.disabled = currentPage === totalPages || totalPages === 0;

    // 如果没有数据或只有一页，显示单个页码
    if (totalPages <= 1) {
        if (totalPages === 1) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'page-btn active';
            pageBtn.textContent = '1';
            pageBtn.addEventListener('click', () => goToPage(1));
            pageNumbers.appendChild(pageBtn);
        }
        return;
    }

    // 多页情况下的页码显示逻辑
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    // 调整起始页，确保显示足够的页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 显示第一页和省略号（如果需要）
    if (startPage > 1) {
        const firstPage = document.createElement('button');
        firstPage.className = 'page-btn';
        firstPage.textContent = '1';
        firstPage.addEventListener('click', () => goToPage(1));
        pageNumbers.appendChild(firstPage);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }
    }

    // 显示中间页码
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', () => goToPage(i));
        pageNumbers.appendChild(pageBtn);
    }

    // 显示最后一页和省略号（如果需要）
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }

        const lastPage = document.createElement('button');
        lastPage.className = 'page-btn';
        lastPage.textContent = totalPages;
        lastPage.addEventListener('click', () => goToPage(totalPages));
        pageNumbers.appendChild(lastPage);
    }

    // 更新统计信息
    updateStatistics();
}

// 跳转到指定页码
function goToPage(page) {
    console.log('跳转页面: 从', currentPage, '到', page);

    if (page < 1 || page > totalPages || page === currentPage) {
        return;
    }

    currentPage = page;
    renderTable(); // 重新请求数据并渲染
}

// 显示加载动画
function showLoader() {
    if (loader) {
        loader.style.display = 'flex';
    }
}

// 隐藏加载动画
function hideLoader() {
    if (loader) {
        loader.style.display = 'none';
    }
}

// 显示成功消息
function showSuccess(message) {
    const alert = document.getElementById('success-alert');
    const messageSpan = document.getElementById('success-message');
    if (alert && messageSpan) {
        messageSpan.textContent = message;
        alert.style.display = 'flex';

        setTimeout(() => {
            alert.style.display = 'none';
        }, 2000);
    }
}

// 显示错误消息
function showError(message) {
    const alert = document.getElementById('error-alert');
    const messageSpan = document.getElementById('error-message');
    if (alert && messageSpan) {
        messageSpan.textContent = message;
        alert.style.display = 'flex';

        setTimeout(() => {
            alert.style.display = 'none';
        }, 2000);
    }
}

// HTML转义函数
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 处理申请操作
function handleApplicationAction(id, action) {
    const application = applications.find(app => app.id === id);
    if (!application) return;

    const actionText = action === 'approve' ? '通过' : '拒绝';
    const apiUrl = action === 'approve' ? 'userAduit/approve' : 'userAduit/reject';

    // 创建自定义弹窗
    const modal = document.createElement('div');
    modal.className = 'custom-modal';
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 1000;
    `;

    modal.innerHTML = `
        <div style="background: white; padding: 20px; border-radius: 8px; width: 400px; max-width: 90%;">
            <h3>${actionText}申请</h3>
            <p>确定要${actionText}用户 "<strong>${application.username}</strong>" 的店主申请吗？</p>
            <div style="margin: 15px 0;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold;">${actionText}理由：</label>
                <textarea 
                    id="reasonInput" 
                    placeholder="请输入${actionText}理由..." 
                    style="width: 100%; height: 80px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; resize: vertical;"
                ></textarea>
            </div>
            <div style="text-align: right; margin-top: 20px;">
                <button id="cancelBtn" style="padding: 8px 16px; margin-right: 10px; border: 1px solid #ddd; background: #f5f5f5; border-radius: 4px; cursor: pointer;">取消</button>
                <button id="confirmBtn" style="padding: 8px 16px; border: none; background: ${action === 'approve' ? '#1890ff' : '#ff4d4f'}; color: white; border-radius: 4px; cursor: pointer;">确定${actionText}</button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // 取消按钮事件
    document.getElementById('cancelBtn').onclick = function() {
        document.body.removeChild(modal);
    };

    // 确定按钮事件
    document.getElementById('confirmBtn').onclick = function() {
        const reasonInput = document.getElementById('reasonInput');
        const reason = reasonInput.value.trim();

        if (!reason) {
            alert(`${actionText}理由不能为空！`);
            reasonInput.focus();
            return;
        }

        // 移除弹窗
        document.body.removeChild(modal);

        // 执行AJAX请求
        showLoader();
        console.log('执行AJAX请求:', reason)
        $.ajax({
            url: apiUrl,
            type: 'POST',
            data: {
                id: id,
                username: $.cookie("adminName"),  // 保持为 username
                aduitDesc: reason
            },
            success: function (data) {
                if (data.code == 200) {
                    showSuccess(`已${actionText}用户 ${application.username} 的店主申请`);
                    renderTable(); // 重新加载数据
                } else {
                    showError(`操作失败: ${data.message}`);
                    hideLoader();
                }
            },
            error: function(xhr, status, error) {
                console.error('操作失败:', error);
                showError('操作失败，请稍后重试');
                hideLoader();
            }
        });
    };

    // 按ESC键关闭弹窗
    modal.onkeydown = function(e) {
        if (e.key === 'Escape') {
            document.body.removeChild(modal);
        }
    };

    // 点击背景关闭弹窗
    modal.onclick = function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };

    // 自动聚焦到输入框
    setTimeout(() => {
        document.getElementById('reasonInput').focus();
    }, 100);
}
// 添加事件监听器
function addEventListeners() {
    // 分页按钮
    prevPage.addEventListener('click', () => {
        if (currentPage > 1) {
            goToPage(currentPage - 1);
        }
    });

    nextPage.addEventListener('click', () => {
        if (currentPage < totalPages) {
            goToPage(currentPage + 1);
        }
    });

    // 每页显示条数选择器
    pageSizeSelect.addEventListener('change', (e) => {
        rowsPerPage = parseInt(e.target.value);
        currentPage = 1; // 重置到第一页
        renderTable();
    });

    // 搜索按钮
    searchBtn.addEventListener('click', () => {
        currentPage = 1; // 重置到第一页
        renderTable();
    });

    // 搜索框回车事件
    username.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            currentPage = 1;
            renderTable();
        }
    });

    // 状态筛选变化
    statusFilter.addEventListener('change', () => {
        currentPage = 1;
        renderTable();
    });

    // 表格按钮事件委托
    tableBody.addEventListener('click', (e) => {
        const target = e.target.closest('button');
        if (!target) return;

        const id = parseInt(target.getAttribute('data-id'));
        const application = applications.find(app => app.id === id);
        if (!application) return;

        if (target.classList.contains('btn-view')) {
            // 查看按钮
            // alert(`查看申请详情\n申请人: ${application.username}\n申请时间: ${application.createdTime}\n状态: ${getStatusText(application.status)}`);
            var userOwnerdata;
            $.ajax({
                url: '/userAduit/getUserOwnerAduitById',
                type: 'POST',
                data: { id: id },
                async: false,
                success: function (data) {
                    if (data.code == 200) {
                        userOwnerdata = data.data;
                        console.log(userOwnerdata);
                    }
                }
            })
            showOwnerAuditModal(userOwnerdata)
        } else if (target.classList.contains('btn-approve')) {
            // 通过按钮
            handleApplicationAction(id, 'approve');
        } else if (target.classList.contains('btn-reject')) {
            // 拒绝按钮
            handleApplicationAction(id, 'reject');
        }
    });

    // 提示框关闭按钮
    document.querySelectorAll('.alert-close').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const alert = e.target.closest('.alert');
            if (alert) {
                alert.style.display = 'none';
            }
        });
    });
}

// 初始化应用
document.addEventListener('DOMContentLoaded', init);
let currentAuditApplication = null;

// 显示店主申请审核详情模态框
function showOwnerAuditModal(applicationData) {
    currentAuditApplication = applicationData;

    // 填充基本信息
    $('#auditApplicationId').text(applicationData.id || '-');
    $('#auditUserId').text(applicationData.userId || '-');
    $('#auditUsername').text(applicationData.username || '-');
    $('#auditPhone').text(applicationData.phone || '-');
    $('#auditEmail').text(applicationData.email || '-');
    $('#auditApplyTime').text(formatDate(applicationData.createdTime) || '-');

    // 设置用户头像
    if (applicationData.icon) {
        $('#auditUserAvatar').attr('src', applicationData.icon);
    }

    // 设置状态
    updateOwnerAuditStatus(applicationData.status);

    // 填充个人资料
    $('#auditRealName').text(applicationData.realname || '未填写');
    $('#auditGender').text(applicationData.gender);
    $('#auditAge').text(applicationData.age ? applicationData.age + '岁' : '未填写');
    $('#auditIdCard').text(applicationData.idCard ? maskIdCard(applicationData.idCard) : '未填写');
    $('#auditBio').text(applicationData.description || '暂无个人简介');

    // 填充申请信息
    $('#auditApplyReason').text(applicationData.aduitReason || '未填写申请理由');
    $('#auditBusinessPlan').text(applicationData.businessPlan || '未填写经营计划');
    $('#auditInvestment').text(applicationData.investment ? `¥${applicationData.investment}` : '未填写');
    $('#auditExperience').text(getExperienceText(applicationData.aduitExperience));


    // 身份证照片
    setupDocumentImages('idCardImages', applicationData.idCardImg || []);

    // 营业执照照片
    setupDocumentImages('businessLicenseImages', applicationData.businessLicense || []);

    // 其他材料
    setupDocumentImages('otherDocuments', applicationData.verifyImg || []);

    // 显示审核信息（如果已审核）
    if (applicationData.status !== 'pending') {
        $('#auditInfoSection').show();
        $('#auditReviewer').text(applicationData.aduitPerson || '-');
        $('#auditReviewTime').text(formatDate(applicationData.aduitTime) || '-');
        $('#auditReviewNote').text(applicationData.aduitDesc || '无备注');

        // 隐藏操作按钮
        $('#auditActionButtons').hide();
    } else {
        $('#auditInfoSection').hide();
        $('#auditActionButtons').show();
    }

    // 显示模态框
    $('#ownerAuditModal').show();
    $('body').css('overflow', 'hidden');
}

// 更新审核状态显示
function updateOwnerAuditStatus(status) {
    const statusBadge = $('#auditStatusBadge');
    statusBadge.removeClass('status-pending status-approved status-rejected');

    switch(status) {
        case 1:
            statusBadge.addClass('status-pending').html('<i class="bi bi-clock"></i> 待审核');
            break;
        case 0:
            statusBadge.addClass('status-approved').html('<i class="bi bi-check-circle"></i> 已通过');
            break;
        case 2:
            statusBadge.addClass('status-rejected').html('<i class="bi bi-x-circle"></i> 已拒绝');
            break;
        default:
            statusBadge.text('-');
    }
}

// 设置证明材料

function setupDocumentImages(containerId, images) {
    const container = $(`#${containerId}`);
    container.empty();
    console.log(images);
    images = JSON.parse(images);

    if (!images || images.length === 0) {
        container.html(`
            <div class="no-documents">
                <i class="bi bi-file-earmark-excel"></i>
                <div>暂无材料</div>
            </div>
        `);
        return;
    }

    images.forEach((image, index) => {
        // 根据文件扩展名判断文件类型
        const fileType = getFileType(image);
        const fileName = getFileNameFromUrl(image);

        let documentHtml = '';

        switch(fileType) {
            case 'pdf':
                documentHtml = `
                    <div class="document-preview-item" data-file-url="${image}">
                        <div class="pdf-preview" onclick="viewDocumentImage('${image}', ${index})">
                            <i class="bi bi-file-earmark-pdf" style="font-size: 48px; color: #dc3545;"></i>
                            <div class="uploading-text" style="color: #28a745;">已上传</div>
                            <div style="font-size: 12px; margin-top: 5px;">${fileName}</div>
                        </div>
                    </div>
                `;
                break;

            case 'image':
                documentHtml = `
                    <div class="document-preview-item" data-file-url="${image}">
                        <div class="image-preview" onclick="viewDocumentImage('${image}', ${index})">
                            <img src="${image}" alt="${fileName}" 
                                 onerror="this.src=''">
                            <div class="document-image-overlay">
                                <i class="bi bi-zoom-in"></i>
                            </div>
                        </div>
                    </div>
                `;
                break;

            case 'word':
                documentHtml = `
                    <div class="document-preview-item" data-file-url="${image}">
                        <div class="word-preview" onclick="viewDocumentImage('${image}', ${index})">
                            <i class="bi bi-file-earmark-word" style="font-size: 48px; color: #2b579a;"></i>
                            <div class="uploading-text" style="color: #28a745;">已上传</div>
                            <div style="font-size: 12px; margin-top: 5px;">${fileName}</div>
                        </div>
                        <button class="document-remove-btn" onclick="removeDocumentImage('${containerId}', '${image}', ${index})">
                            <i class="bi bi-x"></i>
                        </button>
                        <div class="file-name" style="font-size: 12px; margin-top: 5px; text-align: center;">
                            ${fileName.length > 20 ? fileName.substring(0, 20) + '...' : fileName}
                        </div>
                    </div>
                `;
                break;

            case 'excel':
                documentHtml = `
                    <div class="document-preview-item" data-file-url="${image}">
                        <div class="excel-preview" onclick="viewDocumentImage('${image}', ${index})">
                            <i class="bi bi-file-earmark-excel" style="font-size: 48px; color: #217346;"></i>
                            <div class="uploading-text" style="color: #28a745;">已上传</div>
                            <div style="font-size: 12px; margin-top: 5px;">${fileName}</div>
                        </div>
                        <button class="document-remove-btn" onclick="removeDocumentImage('${containerId}', '${image}', ${index})">
                            <i class="bi bi-x"></i>
                        </button>
                        <div class="file-name" style="font-size: 12px; margin-top: 5px; text-align: center;">
                            ${fileName.length > 20 ? fileName.substring(0, 20) + '...' : fileName}
                        </div>
                    </div>
                `;
                break;

            default:
                documentHtml = `
                    <div class="document-preview-item" data-file-url="${image}">
                        <div class="file-preview" onclick="viewDocumentImage('${image}', ${index})">
                            <i class="bi bi-file-earmark" style="font-size: 48px; color: #6c757d;"></i>
                            <div class="uploading-text" style="color: #28a745;">已上传</div>
                            <div style="font-size: 12px; margin-top: 5px;">${fileName}</div>
                        </div>
                        <button class="document-remove-btn" onclick="removeDocumentImage('${containerId}', '${image}', ${index})">
                            <i class="bi bi-x"></i>
                        </button>
                        <div class="file-name" style="font-size: 12px; margin-top: 5px; text-align: center;">
                            ${fileName.length > 20 ? fileName.substring(0, 20) + '...' : fileName}
                        </div>
                    </div>
                `;
        }

        container.append(documentHtml);
    });
}

// 获取文件类型
function getFileType(url) {
    const extension = url.split('.').pop().toLowerCase();

    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
    const pdfExtensions = ['pdf'];
    const wordExtensions = ['doc', 'docx'];
    const excelExtensions = ['xls', 'xlsx', 'csv'];

    if (imageExtensions.includes(extension)) {
        return 'image';
    } else if (pdfExtensions.includes(extension)) {
        return 'pdf';
    } else if (wordExtensions.includes(extension)) {
        return 'word';
    } else if (excelExtensions.includes(extension)) {
        return 'excel';
    } else {
        return 'other';
    }
}

// 从URL中提取文件名
function getFileNameFromUrl(url) {
    // 处理包含查询参数的URL
    const urlWithoutParams = url.split('?')[0];
    // 获取最后一个斜杠后的内容
    const fileName = urlWithoutParams.split('/').pop();
    // 解码URL编码的文件名
    return decodeURIComponent(fileName);
}

// 移除文档图片

// 更新容器状态
function updateContainerState(containerId) {
    const container = $(`#${containerId}`);
    const items = container.find('.document-preview-item');

    if (items.length === 0) {
        container.html(`
            <div class="no-documents">
                <i class="bi bi-file-earmark-excel"></i>
                <div>暂无材料</div>
            </div>
        `);
    }
}

// 查看文档
function viewDocumentImage(url, index) {
    // 根据文件类型决定查看方式
    const fileType = getFileType(url);

    if (fileType === 'image') {
        // 图片预览
        openImageModal(url);
    } else {
        // 其他文件类型，直接下载或在浏览器中打开
        window.open(url, '_blank');
    }
}

// 打开图片预览模态框
function openImageModal(imageUrl) {
    // 这里可以实现图片预览模态框
    const modalHtml = `
        <div class="modal-overlay" id="imagePreviewModal" style="display: flex;">
            <div class="modal-content" style="max-width: 90%; max-height: 90%;">
                <div class="modal-header">
                    <h3 class="modal-title">图片预览</h3>
                    <button class="modal-close" onclick="closeImageModal()">&times;</button>
                </div>
                <div class="modal-body" style="text-align: center; padding: 20px;">
                    <img src="${imageUrl}" alt="预览图片" style="max-width: 100%; max-height: 70vh;">
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary" onclick="downloadFile('${imageUrl}')">
                        <i class="bi bi-download"></i> 下载
                    </button>
                    <button class="btn btn-secondary" onclick="closeImageModal()">关闭</button>
                </div>
            </div>
        </div>
    `;

    $('body').append(modalHtml);
}

// 关闭图片预览模态框
function closeImageModal() {
    $('#imagePreviewModal').remove();
}

// 下载文件
function downloadFile(url) {
    const link = document.createElement('a');
    link.href = url;
    link.download = getFileNameFromUrl(url);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 删除已上传的文件

// 查看证明材料大图
function viewDocumentImage(imageUrl, index) {
    // 创建图片查看器
    let viewer = $('#imageViewerModal');
    if (viewer.length === 0) {
        $('body').append(`
            <div class="image-viewer-modal" id="imageViewerModal">
                <div class="image-viewer-content">
                    <img src="${imageUrl}" alt="证明材料大图">
                    <button class="image-viewer-close" onclick="closeImageViewer()">&times;</button>
                </div>
            </div>
        `);
    } else {
        viewer.find('img').attr('src', imageUrl);
    }

    $('#imageViewerModal').show();
}

function closeImageViewer() {
    $('#imageViewerModal').hide();
}

// 关闭模态框
function closeOwnerAuditModal() {
    $('#ownerAuditModal').hide();
    $('body').css('overflow', 'auto');
    currentAuditApplication = null;
}

// 审核操作
function approveOwnerApplication() {
    if (!currentAuditApplication) return;

    if (confirm('确定要通过这个店主申请吗？')) {
        submitOwnerAuditAction(currentAuditApplication.id, 'approved', '申请通过');
    }
}

function rejectOwnerApplication() {
    if (!currentAuditApplication) return;

    const reason = prompt('请输入拒绝原因：');
    if (reason !== null && reason.trim() !== '') {
        submitOwnerAuditAction(currentAuditApplication.id, 'rejected', reason);
    }
}

function submitOwnerAuditAction(applicationId, status, note) {
    showLoading();

    $.ajax({
        url: '/api/owner-applications/audit',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            applicationId: applicationId,
            status: status,
            reviewNote: note
        }),
        headers: {
            'X-CSRF-TOKEN': getCsrfToken()
        },
        success: function(response) {
            hideLoading();
            if (response.success) {
                showSuccessAlert(status === 'approved' ? '申请已通过' : '申请已拒绝');
                closeOwnerAuditModal();
                // 刷新表格数据
                loadOwnerApplications();
            } else {
                showErrorAlert(response.message || '操作失败');
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showErrorAlert('操作失败: ' + (xhr.responseJSON?.message || error));
        }
    });
}

// 工具函数
function getGenderText(gender) {
    switch(gender) {
        case 'male': return '男';
        case 'female': return '女';
        default: return '未填写';
    }
}

function getExperienceText(experience) {
    if (!experience) return '未填写';

    const experiences = {
        'none': '无经验',
        'less_1': '1年以下',
        '1_3': '1-3年',
        '3_5': '3-5年',
        'more_5': '5年以上'
    };

    return experiences[experience] || experience;
}

function maskIdCard(idCard) {
    if (!idCard || idCard.length < 15) return idCard;
    return idCard.substring(0, 6) + '********' + idCard.substring(idCard.length - 4);
}

function formatDate(dateString) {
    if (!dateString) return '-';
    try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch (e) {
        return '-';
    }
}

function getCsrfToken() {
    return $('meta[name="_csrf"]').attr('content') ||
        $('input[name="_csrf"]').val() ||
        $.cookie('XSRF-TOKEN');
}

// 点击模态框外部关闭
$(document).on('click', function(e) {
    if ($(e.target).is('#ownerAuditModal')) {
        closeOwnerAuditModal();
    }
    if ($(e.target).is('#imageViewerModal')) {
        closeImageViewer();
    }
});

// ESC键关闭
$(document).on('keydown', function(e) {
    if (e.keyCode === 27) {
        closeOwnerAuditModal();
        closeImageViewer();
    }
});